﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSharpAlgorithm
{
    class StableMarriage
    {
        public StableMarriage()
        {
            int testCase = Int32.Parse(TestConsole.ReadLine().Trim());
            while (testCase-- > 0)
            {
                int marriagesCount = Int32.Parse(TestConsole.ReadLine().Trim());
                int[,] preferBoard = new int[marriagesCount + 1, marriagesCount + 1];
                for (int i = 0; i < marriagesCount; i++)
                {
                    string[] input = TestConsole.ReadLine().Trim().Split(' ');
                    int w = Int32.Parse(input[0]);
                    for (int j = 1; j < marriagesCount + 1; j++)
                    {
                        int prefer = Int32.Parse(input[j]);
                        preferBoard[w, prefer] = preferBoard[w, prefer] + j;
                    }
                }
                for (int i = 0; i < marriagesCount; i++)
                {
                    string[] input = TestConsole.ReadLine().Trim().Split(' ');
                    int m = Int32.Parse(input[0]);
                    for (int j = 1; j < marriagesCount + 1; j++)
                    {
                        int prefer = Int32.Parse(input[j]);
                        preferBoard[prefer, m] = preferBoard[prefer, m] + j;
                    }
                }
                for (int c = 0; c < marriagesCount; c++)
                {
                    int minValue = int.MaxValue;
                    int marriedW = 0;
                    int marriedM = 0;
                    for (int w = 1; w < marriagesCount + 1; w++)
                    {
                        for (int m = 1; m < marriagesCount + 1; m++)
                        {
                            if (preferBoard[w, m] < minValue && preferBoard[0, m] == 0 && preferBoard[w, 0] == 0)
                            {
                                marriedW = w;
                                marriedM = m;
                                minValue = preferBoard[w, m];
                            }
                        }
                    }
                    Console.WriteLine(marriedM + " " + marriedW);
                    preferBoard[0, marriedM] = 1;
                    preferBoard[marriedW, 0] = 1;
                }
                Console.WriteLine("");
            }
        }
    }
}
